package com.hyl.controller;

import com.hyl.constans.Constants;
import com.hyl.response.Response;
import com.hyl.service.weixin.IloginService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Request;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author hyl
 * @description 登录的服务
 * @create 2025-06-05 17:30
 */
@Slf4j
@RestController()
@CrossOrigin("*")
@RequestMapping("/api/v1/login")
public class LoginController {
    @Resource
    private IloginService loginService;


    /**
     * http://hyljava.natapp1.cc/api/v1/login/weixin_qrcode_ticket
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "weixin_qrcode_ticket", method = RequestMethod.GET)
    public Response<String> weixinQrCodeTicket() throws Exception {
        try {
            String ticket = loginService.creatQrCodeTicket();
            log.info("生成微信ticket:{}", ticket);
            return Response.<String>builder()
                    .code(Constants.ResponseCode.SUCCESS.getCode())
                    .info(Constants.ResponseCode.SUCCESS.getInfo())
                    .data(ticket)
                    .build();
        } catch (Exception e) {
            log.error("创建二维码ticket异常", e);
            return Response.<String>builder()
                    .code(Constants.ResponseCode.UN_ERROR.getCode())
                    .info(Constants.ResponseCode.UN_ERROR.getInfo())
                    .build();
        }
    }

    /**
     *http://hyljava.natapp1.cc/api/v1/login/check_login
     * @param ticket
     * @return
     */
    @RequestMapping(value = "check_login",method = RequestMethod.GET)
    public Response<String> checkLogin(@RequestParam String ticket){
        try {
            String openidtoken = loginService.checkLogin(ticket);
            log.info("扫码检测登录结果ticket:{},openid:{}",ticket,openidtoken);
            if (StringUtils.isNotBlank(openidtoken)){
                return Response.<String>builder()
                        .code(Constants.ResponseCode.SUCCESS.getCode())
                        .info(Constants.ResponseCode.SUCCESS.getInfo())
                        .data(openidtoken)
                        .build();
            }else {
                return Response.<String>builder()
                        .code(Constants.ResponseCode.NO_LOGIN.getCode())
                        .info(Constants.ResponseCode.NO_LOGIN.getInfo())
                        .build();
            }
        }catch (Exception e){
            log.error("扫码检测登录结果失败ticket:{}",ticket);
            return Response.<String>builder()
                    .code(Constants.ResponseCode.UN_ERROR.getCode())
                    .info(Constants.ResponseCode.UN_ERROR.getInfo())
                    .build();
        }
    }
}